package com.qf.service.impl;/*
 *徐韬
 *2021/10/26
 *19:43
 */

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qf.cache.blacklistCache;
import com.qf.cache.paramsCache;
import com.qf.constons.resultCode;
import com.qf.events.UpdateBlackevents;
import com.qf.exceptions.addDataException;
import com.qf.exceptions.updateException;
import com.qf.mapper.TBlacklistMapper;
import com.qf.pojo.*;
import com.qf.service.TBlacklistService;
import com.qf.utils.CheckPhone;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.naming.Context;
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.PrimitiveIterator;
import java.util.stream.Collectors;

@Service
@Transactional
public class TBlackServiceimpl implements TBlacklistService {
    private paramsCache paramsCache;
@Autowired
    public void setParamsCache(com.qf.cache.paramsCache paramsCache) {
        this.paramsCache = paramsCache;
    }

    private ApplicationContext context;
    @Autowired
    public void setContext(ApplicationContext context) {
        this.context = context;
    }

    blacklistCache blacklistCache;
@Autowired
    public void setBlacklistCache(com.qf.cache.blacklistCache blacklistCache) {
        this.blacklistCache = blacklistCache;
    }

    TBlacklistMapper tBlacklistMapper;
@Autowired
    public void settBlacklistMapper(TBlacklistMapper tBlacklistMapper) {
        this.tBlacklistMapper = tBlacklistMapper;
    }

    @Override
    public void addblack(TBlackList tBlackList) {
        if(tBlackList.isNull(checkType.ADD)){
            throw new addDataException("手机号不符合格式", resultCode.PHONE_NUM_ERROR);
        }



        tBlacklistMapper.addblack(tBlackList);
        context.publishEvent(new UpdateBlackevents());

    }

    @Override
    @Transactional(readOnly = true)
    public PageInfo<TBlackList> showAll(Integer pageNum, Integer pageSize) {



        PageHelper.startPage(pageNum,pageSize);//开始分页，并创建分页信息
//        List<TBlackList> tBlackLists = tBlacklistMapper.selectAll();
//        PageInfo<TBlackList> pageInfo = new PageInfo<>(tBlackLists);
        List<TBlackList> tBlackLists = blacklistCache.getfinlAll();//在缓存中取出集合，通过get方法

//        List<TBlackList> subList = tBlackLists.subList((pageNum - 1) * pageSize, pageNum * pageSize);
//        List<TBlackList> subList = tBlackLists.stream().skip((pageNum - 1) * pageSize).limit(pageSize).collect(Collectors.toList());
//        PageInfo<TBlackList> pageInfo = new PageInfo<>(subList);
//        pageInfo.setTotal(tBlackLists.size());
//        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();//在service中获取一个session
//        TAdminUser user = (TAdminUser) ((ServletRequestAttributes) requestAttributes).getRequest().getSession().getAttribute("user");//将用户信息取出
        MyAuthUser authUser = (MyAuthUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        List<TBlackList> tBlackListList = tBlackLists.stream().filter(black -> {
                    return black.getOwntype() == 1 || black.getCreater() == authUser.getId() || authUser.getType() == 1;
                }//判断用户和查询出来的数据做比较，让用户只能看到自己添加的数据
        ).collect(Collectors.toList());//将数据转换为集合的格式导出
        List<TBlackList> subList = tBlackListList.stream().skip((pageNum - 1) * pageSize).limit(pageSize).collect(Collectors.toList());//将集合姐取  按分页的格式

            PageInfo<TBlackList> pageInfo = new PageInfo<>(subList);
            pageInfo.setTotal(tBlackListList.size());//将总行数给pageinfo

        return pageInfo;
    }

    @Override
    public void updateblack(TBlackList tBlackList) {
        if(tBlackList.isNull(checkType.UPDATE)){
            throw new updateException("更新必须传递主键和手机号",resultCode.DATA_ISNULL);
        }
        TBlackList list = tBlacklistMapper.selectById(tBlackList.getId());//根据当前登录用户的id 查询用户自己所有黑名单信息
        if(tBlackList.getOwntype() != 1 && tBlackList.getCreater() != list.getCreater()){//如果登录的用户不是管理员，并且 登录的用户修改 的不是他自己的信息  抛出异常
                throw new updateException("您没有权限修改该条数据",resultCode.NO_ROOT);

        }
        tBlacklistMapper.updateBlack(tBlackList);
        context.publishEvent(new UpdateBlackevents());//同步缓存

    }

    @Override
    public void deleteBlackByIds(List<Integer> ids) {
        //如果时管理员登录直接删除，
        //传输过来的数据如果有不是自己权限可以删除的，将权限内的删除，
        //取出session  user
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();//在service中获取一个session
        TAdminUser user = (TAdminUser) ((ServletRequestAttributes) requestAttributes).getRequest().getSession().getAttribute("user");//将用户信息取出
        if(user.getType()==1){
            //可以直接删除
            tBlacklistMapper.deleteById(ids);
            return;
        }
        tBlacklistMapper.deleteByIdandcreater(ids,user.getId());
        context.publishEvent(new UpdateBlackevents());

    }

    @Override
    public TBlackList selectById(Long id) {
        return blacklistCache.getById(id);
    }

    @Override
    public List<TBlackList> showAllByparams(TBlackList tBlackList) {
        Class<? extends TBlackList> tBlackListClass = tBlackList.getClass();
        TBlackList instance = null;
        try {
             instance = tBlackListClass.newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        List<String> list = new ArrayList<>();
        Params black = paramsCache.getById("black");
        String param1 = black.getParam1();
        String param2 = black.getParam2();
        String param3 = black.getParam3();
        if(param1!=null){
            list.add(param1);
        }
        if(param2!=null){
            list.add(param2);
        }
        if(param3!=null){
            list.add(param3);
        }
        TBlackList instance1 = instance;
        list.forEach(l->{
            try {
                PropertyDescriptor propertyDescriptor = new PropertyDescriptor(l, tBlackListClass);
                Method readMethod = propertyDescriptor.getReadMethod();
                Method writeMethod = propertyDescriptor.getWriteMethod();
                writeMethod.invoke(instance1,readMethod.invoke(tBlackList ) );
            } catch (IntrospectionException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        });
        System.out.println(instance1);
        List<TBlackList> tBlackListList = tBlacklistMapper.showAllBypramas(instance1);
        return tBlackListList;

    }
}
